package com.yxc.securitydemo1.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxc.securitydemo1.dao.UserMapper;
import com.yxc.securitydemo1.entity.Menu;
import com.yxc.securitydemo1.entity.Role;
import com.yxc.securitydemo1.entity.Userinfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Userinfo> implements UserDetailsService,UserService{

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<Userinfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Userinfo::getUsername,username);
        List<Userinfo> list = userMapper.selectList(lambdaQueryWrapper);
        if(list==null|| list.isEmpty()){
            throw new UsernameNotFoundException("帐户不存在");
        }
        Userinfo user=list.get(0);
        user.setRoles(userMapper.findRolesByUserId(user.getUid()));//从数据库中查询到该用户的所有角色（含权限）
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for(Role role:user.getRoles()){//取出用户的角色，封装到authorities中
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            for(Menu menu:role.getMenus()){ //如果权限精确到权限菜单级别，则要补充这个
                authorities.add(new SimpleGrantedAuthority(menu.getMenuname()));
            }
        }
        //下面的密码一般要加密
        return new User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),authorities);

    }
}